const apiStatus = require('../../apiStatus');
const validHelper = require('../../helpers/validHelper');
const orderService = require('./orderService');
const skuService = require('../productService/skuService');
const wxPay = require('../../providers/wxPay');
const common = require('../../helpers/common');



function setup(app, appRouter){
  /*订单列表*/
  appRouter.post('/api/order/list', async(ctx,next) => {
      let appId = 2;//ctx.appInfo.id;
      let userId = 1;//ctx.user.id;
      let pageIndex = ctx.request.body.pageIndex || 0;
      let pageSize = ctx.request.body.pageSize || 10;
      let type = ctx.request.body.type;

      var miss = validHelper.check([
	          type,"type"
	    ]);
    	if(miss.length > 0){
    		this.apiState = apiState.missArguments(miss);
        return;
    	}
      pageSize = Math.min(100,Math.max(1,pageSize));
	    let offset = pageIndex * pageSize;
	    let limit = pageSize;
      let rows = await orderService.list(appId,userId,offset,limit,type);
      ctx.apiBody = rows;
      next();
  });

  appRouter.post('/api/order/info', async(ctx,next) => {
      let appId = 2;//ctx.appInfo.id;
      let userId = 1;//ctx.user.id;
      let orderNum = ctx.request.body.orderNum;
      var miss = validHelper.check([
	          orderNum,"orderNum"
	    ]);
    	if(miss.length > 0){
    		ctx.apiStatus = {apiStatus:apiStatus.missArguments(miss)};
    		return;
    	}
      let order = await orderService.info(appId,userId,orderNum);
      ctx.apiBody = order == null ? {apiStatus:apiStatus.serverError} : order;
      next();
  });

  appRouter.post('/api/order/add', async(ctx,next) => {
      let appId = 2;//ctx.appInfo.id;
      let userId = 1;//ctx.user.id;
      console.log("参数json:" + JSON.stringify(ctx.request.body));
      let shipType = ctx.request.body.shipType || 0;
      let shippingAmount = ctx.request.body.shipAmount || 0; //运费
      let productAmount = ctx.request.body.productAmount; //商品总金额
      let orderAmount = ctx.request.body.orderAmount; //订单总金额
      let payAmount = ctx.request.body.payAmount;//实际支付金额
      let paymentType = ctx.request.body.paymentType || 0; //支付方式
      let consignee = ctx.request.body.consignee; //收货联系人
      let province = ctx.request.body.province;//省
      let city = ctx.request.body.city;//城市
      let district = ctx.request.body.district;//地区
      let address = ctx.request.body.address;//详细地址
      let mobile = ctx.request.body.mobile;//地区
      let products = ctx.request.body.products || '[]'; //商品集合  json格式
      let addTime = Math.floor(new Date().getTime() / 1000);
      let miss = [];
      miss = validHelper.check([
          shipType,"shipType",
          productAmount,"productAmount",
          orderAmount,"orderAmount",
          payAmount,"payAmount",
          paymentType,"paymentType",
          consignee,"consignee",
          province,"province",
          city,"city",
          district,"district",
          products,"products"
      ]);
      console.log("aa");
      if (miss.length > 0) {
        ctx.body = {apiStatus:apiStatus.missArguments(miss)};
        return;
      }
      //验证商品是否存在
      let isExist = true;
      let isFull = true;
      let isValid = true;
      let list = products;
      for(var i in list) {
        let product = await skuService.getProduct(appId,list[i].productId,list[i].skuId);
        console.log('单商品信息: ' + JSON.stringify(product) + " 商品编号:" + list[i].productId + " 商品: " + list[i] + " count:" + (parseInt(product["salesCount"]) + parseInt(list[i].selectedNumber)));
        isExist = product == null ? false : true;
        isFull = product['totalNumber'] < (parseInt(product["salesCount"]) + parseInt(list[i].count)) ? false : true;
        isValid = parseFloat(product['saleAmount']) != parseFloat(list[i].selectedAmount) ? false : true;
        if (!isExist || !isFull || !isValid) {
          break;
        }
      }

      if (!isExist) {
        ctx.body = {apiStatus: apiStatus.productNotExist};
        return;
      }

      if (!isFull) {
        ctx.body = {apiStatus: apiStatus.productNoQuantity};
        return;
      }

      if (!isValid) {
        ctx.body = {apiStatus: apiStatus.argumentInvalid};
        return;
      }
      console.log("aaaaaa");
      /*验证商品总金额*/
      let flag = await orderService.checkOrderAmountMulit(productAmount,list);
      if (!flag) {
        console.log("订单总金额效验失败：" + 'Price Validate Fail');
        ctx.body = {apiStatus: apiStatus.priceValidateFail};
        return;
      }

      flag = await orderService.checkPayAmount(orderAmount,payAmount,shippingAmount);
      if (!flag) {
        console.log("实际支付金额效验失败：" + 'Price Validate Fail');
        ctx.body = {apiStatus: apiStatus.priceValidateFail};
        return;
      }

      let orderNum = await orderService.getOrderNum(appId);
      orderNum = await orderService.addOrder(userId,appId,addTime,orderNum,productAmount,shippingAmount,orderAmount,payAmount,1,consignee,province,city,district,address,mobile,shipType,paymentType,list);
      if (orderNum != '') {
        ctx.apiBody = {orderNum: orderNum};
        next();
      } else {
        ctx.body = {apiStatus: apiStatus.serverError};
        return;
      }
  });

  appRouter.post('/api/order/prePay', async(ctx,next) => {
    let appId = 2;//ctx.appInfo.id;
    let userId = 1;//ctx.user.id;
    let orderNum = ctx.request.body.orderNum; //订单编号
    let productName = ctx.request.body.productName; //商品名称
    let price = ctx.request.body.price; //支付金额 以分为单位
    let toolType = ctx.request.body.toolType || 2; //支付工具 1 -支付宝  2 -微信  3 -银联
    let attach = ctx.request.body.attach || 1; //支付类型  1  订单  2 还款 3 续租
    let pf = ctx.request.body.pf || ''; //平台  androidphone  ios
    let payType = ctx.request.body.payType || 2; //支付类型 1 支付订金 2 支付全款 3 支付尾款

    var miss = validHelper.check([
        orderNum,"orderNum",
        productName,"productName",
        price,"price"
    ]);
    if (miss.length > 0) {
      ctx.body = {apiStatus:apiStatus.missArguments(miss)};
      return;
    }

    if(price < 0){
        this.body = {apiStatus: apiStatus.priceValidateFail};
        return;
    }

    let isExist = await orderService.checkOrderExist(appId,userId,orderNum,price);
    if (!isExist) {
      ctx.body = {apiStatus: apiStatus.orderNotExist};
      return;
    }

    let body = await wxPay.prePay(productName,orderNum,price * 100,'JSAPI',common.getClientId(),pf,attach,"");
    console.log("返回值：" + body);
    ctx.apiBody = body;
    next();
  });

  appRouter.post('/api/order/check', async(ctx,next) => {
    let appId = 2;//ctx.appInfo.id;
    let userId = 1;//ctx.user.id;
    let orderNum = this.request.body.orderNum;
    let toolType = this.request.body.toolType || 2; //支付工具 1 支付宝 2 微信 3 银联
    let payType = this.request.body.payType || 2; //支付类型 1 订金 2 全款 3 尾款
    let attach = this.request.body.attach || 1; //订单类型 1 订单 2 账单 3 续租

    let miss = validHelper.check([
        orderNum,"orderNum"
    ]);

    if(miss.length > 0){
        ctx.apiStatus = {apiStatus:apiStatus.missArguments(miss)};
        return;
    }

    let flag = await orderService.checkOrderStatus(appId,userId,orderNum,1);
    ctx.apiStatus = flag ? {apiStatus: apiStatus.success} : {apiStatus: apiStatus.serverError};
    next();
  });

  appRouter.post('/api/wxPay/notify', async(ctx,next) => {
    let body = ctx.request.body;
    let json = body.xml;
    let returnCode = 'FAIL';
  	let resultCode = 'Sign is FAIL';
    console.log("body:" + json);
    if (json == null || json == "" || json == undefined) {
      let result = '<xml>';
      result += '<return_code><![CDATA['+ returnCode +']]></return_code>';
      result += '<return_msg><![CDATA['+ resultCode +']]></return_msg>';
      result += '</xml>';
      console.log("回调返回值:" + result);
      ctx.apiBody = result;
      return;
    }

    let sign = await wxPay.getSignByNotify(json);
    console.log("签名结果:" + sign + "微信签名:" + json.sign);
    if(sign != null && sign == json.sign[0]) {
      let trade_no = json.out_trade_no;
      let order = await orderService.getOrderByOrderNo(trade_no);
      if (order) {
        let flag = await orderService.updateOrderStatusByOrderNum(trade_no,3);
        if (flag) {
          returnCode = 'SUCCESS';
          resultCode = 'OK';
        }
      }
    }
    let result = '<xml>';
    result += '<return_code><![CDATA['+ returnCode +']]></return_code>';
    result += '<return_msg><![CDATA['+ resultCode +']]></return_msg>';
    result += '</xml>';
    console.log("回调返回值:" + result);
    ctx.apiBody = result;
    next();
  });

  appRouter.post('/api/order/update', async(ctx,next) => {
    let appId = 2;//ctx.appInfo.id;
    let userId = 1;//ctx.user.id;
    let orderNum = ctx.request.body.orderNum;
    let operStatus = ctx.request.body.operStatus; // COMFIRM_RECEIVE 确认收货  CANCEL_ORDER 取消订单 DEL_ORDER 删除订单 APPLY_REFUND 申请退款
    let msg = ctx.request.body.msg || "";
    let miss = validHelper.check([
        orderNum,"orderNum",
        operStatus,"operStatus"
    ]);

    if(miss.length > 0){
        ctx.apiBody = {apiStatus:apiStatus.missArguments(miss)};
        next();
        return;
    }

    let order = await orderService.getOrderByOrderNum(appId,userId,orderNum);
    if (order) {
      if (operStatus.toUpperCase() == "CANCEL_ORDER") {
        console.log("ok");
        if (order['orderStatus'] == 1 || order['orderStatus'] == 3) {
           let flag = await orderService.updateOrderStatus(appId,userId,orderNum,2);
           if (flag) {
             let list = order.products;
             for (let i in order.products) {
               await skuService.updateSkuStock(appId,list[i].skuId,list[i].productId,list[i].buyCount,2);
             }
             await orderService.doOrderAction(appId,userId,order.id,0,1,"取消订单","");
             ctx.apiBody = {apiStatus: apiStatus.success};
             next();
           } else {
             ctx.apiBody = {apiStatus: apiStatus.serverError};
             next();
           }
        }
      } else if (order['orderStatus'] == 4 && operStatus.toUpperCase() == "COMFIRM_RECEIVE") {
        let flag = await orderService.updateOrderStatus(appId,userId,orderNum,5);
        if (flag) {
          await orderService.doOrderAction(appId,userId,order.id,3,0,"确认收货","");
        }
        ctx.apiBody = flag ? {apiStatus: apiStatus.success} : {apiStatus: apiStatus.serverError};
        next();
      } else if (operStatus.toUpperCase() == "DEL_ORDER") {
        let flag = await orderService.updateOrderStatus(appId,userId,orderNum,9);
        if (flag) {
          await orderService.doOrderAction(appId,userId,order.id,0,2,"删除订单","");
        }
        ctx.apiBody = flag ? {apiStatus: apiStatus.success} : {apiStatus: apiStatus.serverError};
        next();
      } else if ((order['orderStatus'] == 3 && operStatus.toUpperCase() == "APPLY_REFUND") || (order['orderStatus'] == 5 && operStatus.toUpperCase() == "APPLY_REFUND") || (order['orderStatus'] == 6 && operStatus.toUpperCase() == "APPLY_REFUND")) {
        let flag = await orderService.updateOrderStatus(appId,userId,orderNum,7);
        if (flag) {
          await orderService.doOrderAction(appId,userId,order.id,4,0,"申请退款",msg);
        }
        ctx.apiBody = flag ? {apiStatus: apiStatus.success} : {apiStatus: apiStatus.serverError};
        next();
      }
    }else {
       ctx.apiBody = {apiStatus: apiStatus.orderNotExist};
       next();
    }
  });
}

module.exports = setup;
